package com.mapreduce.mapjoin;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class DistributedMapper extends Mapper<LongWritable, Text,Text, NullWritable> {
     //存放pd.txt的数据，key 是产品pid ，value 是产品名称pName
     private Map<String,String> pMap = new HashMap<>();
     private  Text keyOut= new Text();

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        // 获取缓存文件，并把文件pd.txt内容封装到集合
        URI[] cacheFiles = context.getCacheFiles();
        Configuration configuration = context.getConfiguration();
        FileSystem fs = FileSystem.get(configuration);
        //获取到输入流
        FSDataInputStream fsd = fs.open(new Path(cacheFiles[0]));
        //从流中读取数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(fsd, "UTF-8"));
        String line ;
        while ((line=reader.readLine())!=null){
            //01	小米
            String[] data1 = line.split("\t");
            String pid = data1[0];
            String pName = data1[1];
            //key :value
            // 01:小米
            pMap.put(pid,pName);
        }
        //关流
        reader.close();
    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //1001	01	1
        String line = value.toString();//来自order.txt
        String[] data2 = line.split("\t");
        //订单id
        String orderId = data2[0];
        //产品id
        String pid = data2[1];
        //订单数
        String count = data2[2];

        //输出: 订单id   产品名称   订单量
        //     1001     小米       1
        String content = orderId+"\t"+pMap.get(pid)+"\t"+count;
        keyOut.set(content);

      context.write(keyOut,NullWritable.get());
    }
}
